clear;
clc;
global h dataBuffer maxPoints s startTime;

% **先释放旧串口**
if exist('s', 'var') 
    delete(s);
    clear s;
end

% **自动检测串口**
port = serialportlist;
disp("可用串口: " + join(port, ", "));

port = "COM15";  % 请确保 COM15 存在！
baudRate = 115200;
s = serialport(port, baudRate, "DataBits", 8, "StopBits", 1, "Parity", "none");

flush(s);
disp("✅ 串口连接成功，清空缓冲区");

% **初始化数据缓冲**
dataBuffer = [];
maxPoints = 50;

% **创建实时绘图**
figure;
h = animatedline('Color', 'b');
ax = gca;
ax.YLim = [1000, 1500];
ax.XLim = [0, 500];

grid on;

% **初始化时间**
startTime = posixtime(datetime('now'));
updateInterval = 0.01;
lastUpdateTime = 0;

% **主循环**
while true
    try
        if s.NumBytesAvailable >= 6
            rawBytes = read(s, 6, "uint8");

            % **检查帧头**
            if rawBytes(1) == 0xAA && rawBytes(2) == 0x55
                dataBytes = rawBytes(3:6);

                % **转换为 uint32 (Little-Endian)**
                dataBytes = reshape(dataBytes, 1, []);
                receivedNumber = typecast(uint8(dataBytes), "uint32");

                % **转换为 double**
                receivedNumber = double(receivedNumber);

                % **存储数据**
                dataBuffer = [dataBuffer; receivedNumber];
                if length(dataBuffer) > maxPoints
                    dataBuffer = dataBuffer(end - maxPoints + 1:end);
                end

                % **绘图**
                currentTime = posixtime(datetime('now')) - startTime;
                if currentTime - lastUpdateTime > updateInterval
                    addpoints(h, currentTime, receivedNumber);
                    ax.XLim = [currentTime - 50, currentTime];
                    ax.YLim =[min(dataBuffer)-100,max(dataBuffer)+100];
                    drawnow;
                    lastUpdateTime = currentTime;
                end
            else
                disp("⚠️ 帧头错误，丢弃数据 ⚠️");
            end
        end

        pause(updateInterval);

    catch ME
        disp(['主循环错误: ', ME.message]);
        if exist('s', 'var') && isvalid(s)
            delete(s);
        end
        break;
    end
end
